package com.raos.example.web;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.raos.example.dao.UploadDao;
import com.raos.example.dao.UploadDataListener;
import com.raos.example.model.DownloadData;
import com.raos.example.model.UploadData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * TestWeb  原测试见 easyexcel-test
 *
 * @author raos
 * @email 991207823@qq.com
 * @date 2022/12/16 15:56
 */
@RequestMapping("/test")
@RestController
public class TestWeb {

    @Autowired
    private UploadDao uploadDao;

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p> 1. 创建excel对应的实体对象 参照{@link DownloadData}
     * <p> 2. 设置返回的 参数
     * <p> 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "EasyExcel导出Excel测试";
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8").replace("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcelFactory.write(response.getOutputStream(), DownloadData.class)
                // 设置 sheet 名称
                .sheet("模板")
                // 写入数据
                .doWrite(data());
    }


    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @GetMapping("/downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcelFactory.write(response.getOutputStream(), DownloadData.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("模板")
                    .doWrite(data());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 文件上传
     * <p> 1. 创建excel对应的实体对象 参照{@link UploadData}
     * <p> 2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link UploadDataListener}
     * <p> 3. 直接读即可（实体类属性顺序和Excel表列属性对应--不写映射关系）-- 带映射关系时,index=0表示第1列
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        EasyExcelFactory.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDao)).sheet().doRead();
        return "success";
    }

    @PostMapping("/upload2")
    @ResponseBody
    public String upload2(MultipartFile file) throws IOException {
        EasyExcelFactory.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDao)).sheet().doRead();
        return "success";
    }

    private List<DownloadData> data() {
        List<DownloadData> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            DownloadData data = new DownloadData();
            data.setStr("字符串" + i);
            data.setDateTime(new Date());
            data.setDoubleData(new Random().nextDouble());
            list.add(data);
        }
        return list;
    }

}
